import json


class Page:
    page = 1
    size = 15
    offset = 0
    start = 0
    end = 15

    def set_page(self, val):
        i_val = int(val)
        if i_val > 0:
            self.page = i_val
        self.set_offset()

    def set_size(self, val):
        i_val = int(val)
        if i_val > 0:
            self.size = i_val
        self.set_offset()

    def set_offset(self):
        self.offset = (self.page - 1) * self.size
        self.start = self.offset
        self.end = self.offset + self.size


class RawJsonForm:
    dataset = None

    def __init__(self, body):
        try:
            self.dataset = json.loads(body)
        except Exception:
            self.dataset = {}

    def get(self, field, auto_trim=True):
        val = None
        if field in self.dataset:
            val = self.dataset[field]
        if type(val) is str and auto_trim:
            val = val.strip()
        return val

    def get_int(self, field, def_val=0):
        val = _val = def_val
        if field in self.dataset:
            _val = self.dataset[field]
        typ = type(_val)
        if typ is str:
            if _val.isnumeric():
                val = int(_val)
        elif typ is int:
            val = _val
        return val

    def get_page(self):
        page = Page()
        if 'page' in self.dataset:
            page.set_page(self.dataset['page'])
        if 'size' in self.dataset:
            page.set_size(self.dataset['size'])
        return page
